<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import SearchBar from "../../components/SearchBar/SearchBar.vue";
import api from "@/utils/request";

const router = useRouter();
const searchQuery = ref("");
const activeMenu = ref("发现");

const posts = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = 12;
const totalPages = ref(1);
const isLoading = ref(false);
// 标记是否为搜索状态
const isSearching = ref(false);

const userId = Number(localStorage.getItem("userId") || 0);

const menus = ref([
  { id: "发现", label: "发现", icon: "🏠" },
  { id: "发布", label: "发布", icon: "➕" },
  { id: "通知", label: "通知", icon: "🔔" },
  { id: "更多", label: "更多", icon: "☰" }
]);

const goToMenu = (id: string) => {
  if (id === "发布") {
    router.push("/upload"); // 跳转到上传页面
  } else {
    activeMenu.value = id;
  }
};

const filteredPosts = computed(() => {
  if (!searchQuery.value.trim()) return posts.value;
  return posts.value.filter((post) => post.description.includes(searchQuery.value.trim()));
});

function logout() {
  localStorage.removeItem("token");
  router.push("/login");
}

const displayedPosts = computed(() => posts.value);

async function fetchPosts() {
  if (isLoading.value) return;
  isLoading.value = true;

  try {
    const res = await api.get("/content/recommend", {
      params: {
        pageNo: currentPage.value,
        pageSize,
      },
    });

    if (res.data.code === 200) {
      const list = res.data.data;
      // console.log(res.total)
      posts.value = list.map((item: any) => ({
        id: item.videoId,
        image: `data:image/jpeg;base64,${item.image_base64}`,
        description: item.content,
        isEmpty: false
      }));

      totalPages.value = Math.ceil(res.data.total / pageSize);
    } else {
      alert(`获取帖子失败：${res}`);
    }
  } catch (err) {
    console.error("获取帖子失败", err);
  } finally {
    isLoading.value = false;
  }
}

async function searchPosts() {
  if (isLoading.value) return;
  isLoading.value = true;

  try {
    const res = await api.get("/content/search", {
      params: {
        searchQuery: searchQuery.value.trim(),
        pageNo: currentPage.value,
        pageSize,
      },
    });

    if (res.code === 200) {
      const list = res.data.data;  // 和推荐页面一样
      console.log(list);
      posts.value = list.map((item: any) => ({
        id: item.videoId,
        image: `data:image/jpeg;base64,${item.image_base64}`,
        description: item.content,
        isEmpty: false
      }));

      totalPages.value = Math.ceil(res.data.total / pageSize);
    } else {
      alert(`搜索失败：${res.data.message}`);
    }
  } catch (err) {
    console.error("搜索请求失败", err);
    alert("搜索失败，请稍后再试");
  } finally {
    isLoading.value = false;
  }
}


function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    isSearching.value ? searchPosts() : fetchPosts();
  }
}

function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--;
    isSearching.value ? searchPosts() : fetchPosts();
  }
}

async function handleSearch(keyword: string) {
  searchQuery.value = keyword;
  isSearching.value = true;
  currentPage.value = 1; // 搜索默认从第1页开始
  await searchPosts();     // 重新获取帖子
}

function goToProfile() {
  router.push("/my");
}

function goToPost(postId: number) {
  alert(`跳转到帖子ID: ${postId}`);
  router.push(`/post/${postId}`);
}

onMounted(() => {
  fetchPosts();
});
</script>

<template>
  <div class="recommend-page">
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <div class="sidebar-logo">
        <!-- 使用相对路径 -->
        <img src="../../assets/小粉书logo.png" alt="小红书Logo" />
      </div>
      <nav class="sidebar-nav">
        <ul>
          <li
              v-for="menu in menus"
              :key="menu.id"
              @click="goToMenu(menu.id)"
              :class="{ active: menu.id === activeMenu }"
          >
            <span class="icon">{{ menu.icon }}</span>
            <span>{{ menu.label }}</span>
          </li>
        </ul>
      </nav>
      <button class="login-btn" @click="logout">退出账号</button>
    </aside>

    <!-- 主内容区 -->
    <main class="content">
      <header class="top-bar">
        <div class="search-container">
          <SearchBar 
            v-model="searchQuery"
            @search="handleSearch"
          />
        </div>
        <button type="button" class="profile-btn" @click="goToProfile">我的主页</button>
      </header>

      <div class="content-list">
        <div
            v-for="post in displayedPosts"
            :key="post.id"
            class="post-item"
            @click="!post.isEmpty && goToPost(post.id)"
            :class="{ 'empty-post': post.isEmpty }"
        >
          <img :src="post.image" alt="post image" class="post-image" />
          <p class="post-desc">{{ post.description }}</p>
        </div>
      </div>

      <div class="pagination-controls">
        <button @click="prevPage" :disabled="currentPage === 1 || isLoading">上一页</button>
        <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
        <button @click="nextPage" :disabled="currentPage === totalPages || isLoading">下一页</button>
      </div>

    </main>
  </div>
</template>

<style src="./Recommend.css"></style>